import Cookies from 'js-cookie';

/**
 * 异步设置 Cookie（value 为 JSON 对象）
 * @param key 键
 * @param value JSON 对象值
 * @param options 配置选项
 * @returns Promise 对象
 */
export const asyncSetCookie = (key: string, value: object, options?: Cookies.CookieAttributes): Promise<void> => {
    return new Promise((resolve) => {
        Cookies.set(key, JSON.stringify(value), options);
        resolve();
    });
};

/**
 * 异步获取 Cookie 并解析为对象
 * @param key 键
 * @returns Promise 对象，包含解析后的对象值，如果不存在或解析失败则为 undefined
 */
export const asyncGetCookie = (key: string): Promise<any | undefined> => {
    return new Promise((resolve) => {
        const cookieValue = Cookies.get(key);
        try {
            resolve(cookieValue ? JSON.parse(cookieValue) : undefined);
        } catch (error) {
            resolve(undefined);
        }
    });
};

/**
 * 异步删除 Cookie
 * @param key 键
 * @returns Promise 对象
 */
export const asyncRemoveCookie = (key: string): Promise<void> => {
    return new Promise((resolve) => {
        Cookies.remove(key);
        resolve();
    });
};

/**
 * 异步清空所有 Cookie
 * @returns Promise 对象
 */
export const asyncClearAllCookies = (): Promise<void> => {
    return new Promise((resolve) => {
        const cookies = Cookies.get();
        for (const key in cookies) {
            Cookies.remove(key);
        }
        resolve();
    });
};